const {sign, verify} = require("jsonwebtoken");

async function checkToken(req) {
  const headersArr = req.headers?.authorization ? req.headers.authorization.split(' ') : []
  const token = headersArr.length === 2 ? headersArr[1] : ''
  if (headersArr[0] !== 'gddz' || token.length === 0) {
    return {
      loginStatus: false,
      msg: {
        code: 401,
        msg: '账号未登录，请先登录',
        data: null
      }
    }
  }else {
    const mData = await getUserIdForToken(token)
    if (mData.loginStatus) {
      const dateTime = global.commonFun.getNowTime()
      let updateSql = `UPDATE token SET updateTime = ? WHERE token = ?`
      const updateSqlParams = [dateTime, token];
      const updateStatus = await global.sql(updateSql, updateSqlParams)
      let selectSql = `SELECT * FROM token WHERE token="${token}" `;
      const selectRows = await global.sql(selectSql)
      if (updateStatus.status) {
        const loginRows = {
          ...mData.data,
          ...selectRows.data[0]
        }
        delete loginRows.id // 删除 id 字段
        return {
          loginRows: loginRows,
          loginStatus: true,
          msg: '请求成功'
        }
      }else {
        return delToken(token)
      }
    }else {
      // return delToken(token)
    }
  }
}

async function delToken(token) {
  const delSql = `DELETE FROM token WHERE token="${token}"`
  const res = await global.sql(delSql)
  if (res.status) {
    return {
      loginStatus: false,
      msg: {
        code: 401,
        msg: '账号未登录，请先登录',
        data: null
      }
    }
  }
}

function getToken(user) {
  try {
    const data = {
      phone: user.phone,
      userName: user.userName,
      userId: user.id,
    }
    const options = {
      // expiresIn: 50,
      expiresIn: 4 * 60 * 60
    }
    return sign(data, `winGundam00`, options)
  }catch (e) {
    return e
  }
}

// 解析 token 里面的 userId
async function getUserIdForToken(token) {
  try {
    const data = verify(token, 'winGundam00')
    return {
      loginStatus: true,
      data: data
    }
  } catch (e) {
    return {
      loginStatus: false,
      data: null
    }
  }
}


exports.getToken = getToken
exports.checkToken = checkToken
